package com.example.reservationbilliards.task;

import com.example.reservationbilliards.config.UserConfigLoader;
import com.example.reservationbilliards.pojo.LoginRequest;
import com.example.reservationbilliards.pojo.LoginResponse;
import com.example.reservationbilliards.pojo.UserConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@Slf4j
public class TokenCacheTasks {

    private final Map<String, String> tokenCache = new ConcurrentHashMap<>();
    @Autowired
    UserConfigLoader userConfigLoader;
    @Autowired
    private RestTemplate restTemplate;

    // 提前5分钟获取Token
    @Scheduled(cron = "${reservation.cron.getTokencron}") // 工作日早上8点23分执行
    //@Scheduled(initialDelay = 1000*5, fixedDelay = 1000 * 60 * 60 * 24)
    public void preFetchTokens() {
        tokenCache.clear();
        List<UserConfig> userConfigs = userConfigLoader.userConfigs();
        for (UserConfig userConfig : userConfigs) {
            String token = login(userConfig);
            if (token != null) {
                tokenCache.put(userConfig.getMobile(), token);
                log.info("用户{}获取令牌,token:{} ", userConfig.getMobile(), token);
            }
        }
    }

    private String login(UserConfig userConfig) {
        String loginUrl = "https://opapp.grandjoy.com/api/login/login?projectId=1&userId=" + userConfig.getUserId();

        LoginRequest loginRequest = new LoginRequest();
        loginRequest.setAppVersion("1.1.12");
        loginRequest.setDeviceNum(null);
        loginRequest.setImsi(null);
        loginRequest.setDeviceType("20");
        loginRequest.setSkinClass("light-theme");
        loginRequest.setOriginType("10");
        loginRequest.setVersion("1.0");
        loginRequest.setTimestamp(System.currentTimeMillis());
        loginRequest.setToken("");
        loginRequest.setProjectId(userConfig.getProjectId());

        LoginRequest.LoginData loginData = new LoginRequest.LoginData();
        loginData.setPassword(userConfig.getPassword());
        loginData.setMobile(userConfig.getMobile());
        loginData.setMobileModel(userConfig.getMobileModel());
        loginData.setMobileSystemVersion(userConfig.getMobileSystemVersion());
        loginData.setType(userConfig.getType());
        loginRequest.setData(loginData);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<LoginRequest> requestEntity = new HttpEntity<>(loginRequest, headers);

        ResponseEntity<LoginResponse> responseEntity = restTemplate.postForEntity(loginUrl, requestEntity, LoginResponse.class);

        if (responseEntity.getStatusCode() == HttpStatus.OK && responseEntity.getBody() != null) {
            if (responseEntity.getBody().getCode().equals("1")) {
                log.info("登录成功!");
                return responseEntity.getBody().getResult().getToken();
            }
        }
        return null;
    }

    public String getToken(String mobile) {
        return tokenCache.get(mobile);
    }
}